package com.gxd.base.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.gxd.base.entity.*;
import com.gxd.base.utils.ConverMapToObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gxd.base.mapper.ManagerMapper;
import com.gxd.base.utils.MD5;

@Service
public class ManagerService {
	
	@Autowired
	private ManagerMapper managerDao;

	/**
	 * 登陆
	 * @param userPwd 用户密码
	 * @return
	 */
	public Map<String, Object> login(String userCode, String userPwd) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User userInfo = managerDao.getUserByCode(userCode);
		if(userInfo != null){
			String inPwd = MD5.passwordEncrypt(userPwd);
			String dbPwd = userInfo.getUserPassword();
			if(inPwd.equals(dbPwd)){
				resultMap.put("code", 1);// 登陆成功
				resultMap.put("status", "ok");
				resultMap.put("currentAuthority", "admin");
				userInfo.setUserPassword("");
				resultMap.put("userInfo", userInfo);
			}else{
				resultMap.put("code", 2);// 密码错误
			}
		}else{
			resultMap.put("code", 0);// 用户不存在
		}
		return resultMap;
	}
	/**
	 * 获取用户的所有权限及角色
	 * @param userId
	 * @return
	 */
	public Map<String, Object> getUserFunAndRole(int userId){
		// 角色列表
		List<Role> userRoles = managerDao.getRoleByUserId(userId);
		// 权限列表
		List<Function> userFuns = managerDao.getFunctionByUserId(userId);
		// 返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("roles", userRoles);
		resultMap.put("funs", userFuns);
		return resultMap;
	}
	/**
	 * 根据用户ID，获取用户记录
	 * @param userId
	 * @return
	 */
	public User getUserById(int userId){
		return managerDao.getUserById(userId);
	}
	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	public Map<String, Object> addUser(User user) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			User userInfo = managerDao.getUserByCode(user.getUserCode());
			if(userInfo == null){
				user.setModifyDate(new Date());
				user.setUserPassword(MD5.passwordEncrypt(user.getUserPassword()));
				managerDao.addUser(user);
				resultMap.put("code", 1);
				resultMap.put("msg", "注册成功");
			}else{
				resultMap.put("code", 2);
				resultMap.put("msg", "工号已存在");
			}
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 获取全部用户
	 * @return
	 */
	public Map<String, Object> getUserList(Map<String, Object> paramMap){
		String userCode = paramMap.get("userCode")==null?"":paramMap.get("userCode").toString();
		String userName = paramMap.get("userName")==null?"":paramMap.get("userName").toString();
		String userPassword = paramMap.get("userPassword")==null?"":paramMap.get("userPassword").toString();
		StringBuffer sql = new StringBuffer();
		if(userCode != null && !userCode.equals("")){
			sql.append(" and user_code like '%"+userCode+"%'");
		}
		if(userName != null && !userName.equals("")){
			sql.append(" and user_name like '%"+userName+"%'");
		}
		if(userPassword != null && !userPassword.equals("")){
			String userPwd = MD5.passwordEncrypt(userPassword);
			sql.append(" and user_password = '"+userPwd+"'");
		}
		// 分页
		int currentPage = paramMap.get("currentPage")==null?0:Integer.parseInt(paramMap.get("currentPage").toString());
		Page page = new Page(currentPage);
		int count = managerDao.getUsersCount(sql.toString());
		page.setTotalSize(count);
		page.setTotalPage(page.getTotalPage());
		int beginSize = page.getBeginSize();
		sql.append(" limit "+page.getPageSize()+" offset "+(beginSize==0?0:beginSize-1));
		List<User> userList = managerDao.getUserList(sql.toString());
		for(User u : userList){
			u.setModifyDateStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(u.getModifyDate()));
		}
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("page", page);
		rsMap.put("list", userList);
		return rsMap;
	}
	/**
	 * 根据用户工号，获取用户
	 * @param userCode 工号
	 * @return
	 */
	public User getUserByCode(String userCode) {
		return managerDao.getUserByCode(userCode);
	}
	/**
	 * 根据工号，冻结账号：0未冻结   1已冻结
	 * @param userCode 工号
	 * @return
	 */
	public Map<String, Object> updateUserState(String userCode) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			User user = managerDao.getUserByCode(userCode);
			String oldState = user.getUserState();
			oldState = oldState.equals("1")?"0":"1";
			Date nowDate = new Date();
			managerDao.updateUserState(userCode, oldState, nowDate);
			resultMap.put("code", 1);
			resultMap.put("msg", "状态修改成功");
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 修改用户信息
	 * @param request
	 * @return
	 */
	public Map<String, Object> updateUser(User user) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			User oldInfo = managerDao.getUserById(user.getUserId());
			// 如果新编码与旧编码不一致，那么就需要判断新编码是否与其他编码重复
			if(oldInfo != null && !user.getUserCode().equals(oldInfo.getUserCode())){
				User u = managerDao.getUserByCode(user.getUserCode());
				if(u != null){
					resultMap.put("code", 2);
					resultMap.put("msg", "用户编码已存在");
					return resultMap;
				}
			}
			user.setModifyDate(new Date());
			managerDao.updateUser(user);
			resultMap.put("code", 1);
			resultMap.put("msg", "用户信息修改成功");
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 修改密码
	 * @param user
	 */
	public void updateUserPwd(User user){
		user.setUserPassword(MD5.passwordEncrypt(user.getUserPassword()));
		managerDao.updateUserPwd(user);
	}
	/**
	 * 获取所有单位
	 * @return
	 */
	private int orgLevel01 = 0;
	private int orgLevel02 = 0;
	private int orgLevel03 = 0;
	public Organization getOrganizationTree() {
		Organization parentOrg = managerDao.getParentOrg();
		int parentOrgId = parentOrg.getOrgId();
		Organization org =  getChildOrg(parentOrg, parentOrgId);
		orgLevel01 = 0;
		orgLevel02 = 0;
		orgLevel03 = 0;
		return org;
	}
	private Organization getChildOrg(Organization org, int parentOrgId){
		if(org.getOrgLevel().equals("1")) orgLevel01 ++;
		if(org.getOrgLevel().equals("2")) {
			orgLevel02 ++;
			orgLevel03 = 0;
		};
		if(org.getOrgLevel().equals("3")) orgLevel03 ++;
		String orgLevelStr = orgLevel01+"";
		if(orgLevel02 > 0) orgLevelStr += "-" + orgLevel02;
		if(orgLevel03 > 0) orgLevelStr += "-" + orgLevel03;
		org.setOrgLevelFormat(orgLevelStr);
		List<Organization> childOrgList = managerDao.getOrgByParentOrgId(parentOrgId);
		if(childOrgList.size() > 0){
			List<Organization> tempList = new ArrayList<Organization>();
			for(Organization o : childOrgList){
				tempList.add(getChildOrg(o, o.getOrgId()));
				org.setChildOrgList(tempList);
			}
			orgLevel03 = 0;
		}
		return org;
	}
	/**
	 * 获取所有地区
	 * @return
	 */
	private int areaLevel01 = 0;
	private int areaLevel02 = 0;
	private int areaLevel03 = 0;
	public Area getAreaTree() {
		List<Area> provinceList = managerDao.getProvince();
		Area rsArea = getChildArea(provinceList.get(0), provinceList.get(0).getAreaId());
		areaLevel01 = 0;
		areaLevel02 = 0;
		areaLevel03 = 0;
		return rsArea;
	}
	private Area getChildArea(Area area, String areaId){
		if(area.getAreaLevel().equals("1")) areaLevel01 ++;
		if(area.getAreaLevel().equals("2")) {
			areaLevel02 ++;
			areaLevel03 = 0;
		};
		if(area.getAreaLevel().equals("3")) areaLevel03 ++;
		String areaLevelStr = areaLevel01+"";
		if(areaLevel02 > 0) areaLevelStr += "-" + areaLevel02;
		if(areaLevel03 > 0) areaLevelStr += "-" + areaLevel03;
		area.setAreaLevelFormat(areaLevelStr);
		List<Area> childAreaList = managerDao.getChildAreaById(areaId);
		if(childAreaList.size() > 0){
			List<Area> tempList = new ArrayList<Area>();
			for(Area a : childAreaList){
				tempList.add(getChildArea(a, a.getAreaId()));
				area.setChildAreaList(tempList);
			}
		}
		return area;
	}
	/**
	 * 获取所有单位
	 * @param org
	 * @return
	 */
	public List<Organization> getOrganizationList(Organization org) {
		String orgName = org.getOrgName()==null?"":org.getOrgName();
		int parentId = org.getParentId();
		StringBuffer sql = new StringBuffer();
		if(orgName != null && !orgName.equals("")){
			sql.append(" and org_name like '%"+orgName+"%'");
		}
		if(parentId > 0){
			sql.append(" and org_id = "+parentId+"");
		}
		List<Organization> orgList = managerDao.getOrganizationList(sql.toString());
		List<Organization> rsList = new ArrayList<Organization>();
		for(int i=0; i<orgList.size(); i++){
			rsList.addAll(orderOrgList(rsList, orgList, orgList.get(i).getOrgId(), String.valueOf(i+1)));
		}
		return orgList;
	}
	
	private List<Organization> orderOrgList(List<Organization> rsList, List<Organization> list, int orgId, String orgLevel){
		if(orgId == 0){
			orgId = list.get(0).getOrgId();
		}
		for(Organization o : list){
			if(o.getParentId() == orgId && o.getOrgLevel().equals(orgLevel)){
				rsList.add(o);
			}
		}
		return rsList;
	}
	/**
	 * 新增部门
	 * @param org
	 * @return
	 */
	public Map<String, Object> addOrganization(Organization org){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			int orgCount = managerDao.getOrganizationByCode(org.getOrgCode());
			if(orgCount == 0){
				org.setModifyDate(new Date());
				managerDao.addOrganization(org);
				result.put("code", 1);
				result.put("msg", "部门添加成功");
			}else{
				result.put("code", 2);
				result.put("msg", "部门编码已存在");
			}
		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", e.getMessage());
		}
		return result;
	}
	/**
	 * 修改部门
	 * @param org
	 * @return
	 */
	public Map<String, Object> updateOrganization(Organization org){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Organization oldOrg = managerDao.getOrgById(org.getOrgId());
			// 如果新编码与旧编码不一致，则需要检查新编码是否与其他编码重复
			if(oldOrg != null && !org.getOrgCode().equals(oldOrg.getOrgCode())){
				int oCon = managerDao.getOrganizationByCode(org.getOrgCode());
				if(oCon > 0){
					result.put("code", 2);
					result.put("msg", "部门编码已存在");
					return result;
				}
			}
			// 获取当前部门的级别（上级部门的级别 + 1 = 当前部门级别 ）
			String orgLevel = "0";
			Organization parentOrg = managerDao.getOrgById(org.getParentId());
			if(parentOrg != null){
				orgLevel = String.valueOf(Integer.parseInt(parentOrg.getOrgLevel())+1);
			}
			// 开始写入
			org.setOrgLevel(orgLevel);
			org.setModifyDate(new Date());
			String stateCode = "0";
			if(org.getStateCode() != null){
				if(!org.getStateCode().equals("")) stateCode = org.getStateCode();
			}
			org.setStateCode(stateCode);
			managerDao.updateOrganization(org);
			result.put("code", 1);
			result.put("msg", "部门修改成功");
		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", e.getMessage());
		}
		return result;
	}
	/**
	 * 根据部门ID，获取部门记录
	 * @param orgId
	 * @return
	 */
	public Organization getOrgById(int orgId){
		return managerDao.getOrgById(orgId);
	}
	/**
	 * 获取所有角色
	 * @param role
	 * @return
	 */
	public List<Role> getRoleList(Role role) {
		String roleName = role.getRoleName()==null?"":role.getRoleName();
		StringBuffer sql = new StringBuffer();
		if(!roleName.equals("")){
			sql.append(" and role_name like '%"+roleName+"%'");
		}
		List<Role> roleList = managerDao.getRoleList(sql.toString());
		for(Role r : roleList){
			r.setModifyDateStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(r.getModifyDate()));
		}
		return roleList;
	}
	/**
	 * 根据角色ID，修改角色状态
	 * @param role
	 * @return
	 */
	public Map<String, Object> updateRoleState(int roleId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Role roleInfo = managerDao.getRoleById(roleId);
			String stateCode = roleInfo.getStateCode().equals("0")?"1":"0";
			managerDao.updateRoleState(roleId, stateCode);// 修改角色状态
			result.put("code", 1);
			result.put("msg", "角色状态修改成功");
		} catch (Exception e) {
			result.put("code", 0);
			result.put("msg", e.getMessage());
		}
		return result;
	}
	/**
	 * 根据角色，获取权限列表
	 * 考虑到以后方便维护，将根据角色/用户获取权限方法分开
	 * @param function
	 * @param role
	 * @return
	 */
	public List<Function> getFunctionListByRole(Function function, Role role) {
		String funName = function.getFunctionName()==null?"":function.getFunctionName();
		String funDesc = function.getFunctionDesc()==null?"":function.getFunctionDesc();
		StringBuffer sql = new StringBuffer();
		if(!funName.equals("")){
			sql.append(" and function_name like '%"+funName+"%'");
		}
		if(!funDesc.equals("")){
			sql.append(" and function_desc like '%"+funDesc+"%'");
		}
		List<Function> allFunList = managerDao.getFunctionList(sql.toString());
		// 获取当前角色下的权限
		List<Function> funList = managerDao.getFunctionByRoleId(role.getRoleId());
		for(Function allFun : allFunList){
			allFun.setModifyDateStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(allFun.getModifyDate()));
			// 写入状态：当前用户 是否拥有此权限
			allFun.setRoleHaveFunction(false);
			for(Function fun : funList){
				if(allFun.getFunctionId() == fun.getFunctionId()){
					allFun.setRoleHaveFunction(true);
				}
			}
		}
		return allFunList;
	}
	/**
	 * 根据用户，获取权限列表
	 * 考虑到以后方便维护，将根据角色/用户获取权限方法分开
	 * @param function
	 * @param user
	 * @return
	 */
	public List<Function> getFunListByUserId(Function function, User user) {
		String funName = function.getFunctionName()==null?"":function.getFunctionName();
		StringBuffer sql = new StringBuffer();
		if(!funName.equals("")){
			sql.append(" and function_name like '%"+funName+"%'");
		}
		sql.append(" and state_code = '0'");
		List<Function> allFunList = managerDao.getFunctionList(sql.toString());
		// 获取当前用户下的权限
		List<Function> funList = managerDao.getFunctionByUserId(user.getUserId());
		for(Function allFun : allFunList){
			allFun.setModifyDateStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(allFun.getModifyDate()));
			// 写入状态：当前用户 是否拥有此权限
			allFun.setRoleHaveFunction(false);
			for(Function fun : funList){
				if(allFun.getFunctionId() == fun.getFunctionId()){
					allFun.setRoleHaveFunction(true);
				}
			}
		}
		return allFunList;
	}
	/**
	 * 根据用户，获取角色列表
	 * @param role
	 * @param user
	 * @return
	 */
	public List<Role> getRolesByUser(Role role, User user) {
		String roleName = role.getRoleName()==null?"":role.getRoleName();
		StringBuffer sql = new StringBuffer();
		if(!roleName.equals("")){
			sql.append(" and role_name like '%"+roleName+"%'");
		}
		sql.append(" and state_code = '0'");
		List<Role> allRoleList = managerDao.getRoleList(sql.toString());// 全部角色列表
		List<Role> userRoleList = managerDao.getRoleByUserId(user.getUserId());// 用户所拥有的角色
		for(Role all : allRoleList){
			all.setUserHaveRole(false);
			for(Role ur : userRoleList){
				if(all.getRoleId() == ur.getRoleId()){
					all.setUserHaveRole(true);
				}
			}
		}
		return allRoleList;
	}
	/**
	 * 获取权限列表
	 * @param fun
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page getFunctionList(Map<String, Object> paramMap){
		String funName = paramMap.get("functionName")==null?"":paramMap.get("functionName").toString();
		StringBuffer sql = new StringBuffer();
		if(!funName.equals("")){
			sql.append(" and function_name like '%"+funName+"%'");
		}
		// 分页
		int currentPage = paramMap.get("currentPage")==null?0:Integer.parseInt(paramMap.get("currentPage").toString());
		Page page = new Page(currentPage);
		int count = managerDao.getFunctionList("").size();
		page.setTotalSize(count);
		page.setTotalPage(page.getTotalPage());
		int beginSize = page.getBeginSize();
		sql.append(" limit "+page.getPageSize()+" offset "+(beginSize==0?0:beginSize-1));
		List<Function> allFunList = managerDao.getFunctionList(sql.toString());
		// 格式化日期
		for(Function f : allFunList){
			f.setModifyDateStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(f.getModifyDate()));
		}
		// 转换
		List<Map<String, Object>> objListMap = new ArrayList<Map<String,Object>>();
		for(Function f : allFunList){
			Map<String, Object> map = (Map<String, Object>) ConverMapToObject.objectToMap(f);
			objListMap.add(map);
		}
		page.setList(objListMap);
		return page;
	}
	/**
	 * 修改权限状态
	 * @param fun
	 * @return
	 */
	public Map<String, Object> updateFunState(Function fun) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			int funId = fun.getFunctionId();
			Function funInfo = managerDao.getFunctionById(funId);
			String stateCode = funInfo.getStateCode();
			stateCode = stateCode.equals("0")?"1":"0";
			Date nowDate = new Date(); 
			managerDao.updateFunState(funId, stateCode, nowDate);// 修改权限状态
			resultMap.put("code", 1);
			resultMap.put("msg", "修改权限状态成功");
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 根据权限ID，获取权限记录
	 * @param function
	 * @return
	 */
	public Function getFunctionById(Function function){
		return managerDao.getFunctionById(function.getFunctionId());
	}
	/**
	 * 给用户赋予权限
	 * @param userId
	 * @param funArray
	 * @return
	 */
	public Map<String, Object> setUserFunction(int userId, String funArray) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 修改用户权限状态：有权限被禁用掉的，将状态改为启用
			managerDao.updateUserFunState(userId, funArray);
			// 获取当前用户下的权限（不限制状态）
			List<Function> userFunList = managerDao.getAllFunctionByUserId(userId);
			// 用户选择的权限
			String[] selectedFuns = funArray.split(",");
			// 记录需要添加的权限
			boolean isAdd = true;
			List<Integer> newFunList = new ArrayList<Integer>();
			for(int i=0; i<selectedFuns.length; i++){
				isAdd = true;
				for(Function uf : userFunList){
					if(uf.getFunctionId() == Integer.parseInt(selectedFuns[i])){
						isAdd = false;
						break;
					}
				}
				if(isAdd){
					newFunList.add(Integer.parseInt(selectedFuns[i]));
				}
			}
			// 没有该权限的，则添加
			UserFunction uf = null;
			for(Integer newFun : newFunList){
				uf = new UserFunction();
				uf.setUserId(userId);
				uf.setFunctionId(newFun);
				uf.setModifyDate(new Date());
				managerDao.addUserFunction(uf);
			}
			resultMap.put("code", 1);
			resultMap.put("msg", "权限赋予成功");
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 给用户赋予角色
	 * @param parseInt
	 * @param funArray
	 * @return
	 */
	public Map<String, Object> setUserRole(int userId, String funArray) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 修改用户角色状态：有角色被禁用掉的，将状态改为启用
			managerDao.updateUserRoleState(userId, funArray);
			// 获取当前用户下的角色（不限制状态）
			List<Role> userRoleList = managerDao.getAllRoleByUserId(userId);
			// 用户选择的权限
			String[] selectedRoles = funArray.split(",");
			// 记录需要添加的权限
			List<Integer> newRoleList = new ArrayList<Integer>();
			boolean isAdd = true;
			for(int i=0; i<selectedRoles.length; i++){
				isAdd = true;
				for(Role ur : userRoleList){
					if(ur.getRoleId() == Integer.parseInt(selectedRoles[i])){
						isAdd = false;
						break;
					}
				}
				if(isAdd){
					newRoleList.add(Integer.parseInt(selectedRoles[i]));
				}
			}
			// 没有该角色的，则添加
			UserRole ur = null;
			for(Integer newRole : newRoleList){
				ur = new UserRole();
				ur.setUserId(userId);
				ur.setRoleId(newRole);
				ur.setModifyDate(new Date());
				managerDao.addUserRole(ur);
			}
			resultMap.put("code", 1);
			resultMap.put("msg", "角色赋予成功");
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 添加角色
	 * @param role 角色对象
	 * @return
	 */
	public Map<String, Object> addRole(HttpServletRequest request, Role role){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String msg = "";
		try {
			String roleCode = role.getRoleCode();
			Role roleInfo = managerDao.getRoleByCode(roleCode);
			if(roleInfo == null){
				role.setModifyDate(new Date());
				managerDao.addRole(role);
				resultMap.put("code", 1);
				msg = "角色添加成功";
				resultMap.put("msg", msg);
				// 给角色赋权
				try {
					String funArray = request.getParameter("funArray")==null?"":request.getParameter("funArray");
					Role newRoleInfo = managerDao.getRoleByCode(role.getRoleCode());
					setRoleFunction(newRoleInfo, funArray);
					resultMap.put("code", 3);
					msg += "，角色赋予权限成功";
					resultMap.put("msg", msg);
				} catch (Exception e) {
					resultMap.put("code", 4);
					msg += "，但是给角色赋予权限失败。错误信息："+e.getMessage();
					resultMap.put("msg", msg);
				}
			}else{
				resultMap.put("code", 2);
				resultMap.put("msg", "角色编码已存在");
			}
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 角色赋权
	 * @param roleId 角色ID
	 * @param funArray 用户选中的权限（111,222,333）
	 */
	public void setRoleFunction(Role role, String funArray){
		managerDao.updateRoleFunState(role.getRoleId(), funArray);// 修改角色权限状态
		List<Function> roleFunList = managerDao.getFunctionByRoleId(role.getRoleId());// 获取角色下的所有权限
		List<Integer> newRoleFuns = new ArrayList<Integer>();// 需要新增的角色权限
		boolean isAdd = true;
		for(String s : funArray.split(",")){
			isAdd = true;
			for(Function f : roleFunList){
				if(Integer.parseInt(s) == f.getFunctionId()){
					isAdd = false;
					break;
				}
			}
			if(isAdd){
				newRoleFuns.add(Integer.parseInt(s));
			}
			
		}
		// 入库
		for(Integer f : newRoleFuns){
			managerDao.setRoleFunction(role.getRoleId(), f, new Date());
		}
	}
	/**
	 * 添加权限
	 * @param role
	 * @return
	 */
	public Map<String, Object> addFunction(HttpServletRequest request, Function fun){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String rsMsg = "";
		try {
			String funCode = fun.getFunctionCode();
			Function funInfo = managerDao.getFunctionByCode(funCode);
			if(funInfo == null){
				fun.setModifyDate(new Date());
				managerDao.addFunction(fun);
				resultMap.put("code", 1);
				resultMap.put("msg", "权限添加成功");
				// 给权限分配菜单
				String menuIds = request.getParameter("menuIds")==null?"":request.getParameter("menuIds");
				if(!menuIds.equals("")){
					try {
						managerDao.addFunctionMenus(fun.getFunctionId(), menuIds);
						rsMsg += "，添加权限菜单成功";
					} catch (Exception e) {
						resultMap.put("code", 3);
						rsMsg += "，添加权限菜单失败"+e.getMessage();
						resultMap.put("msg", rsMsg);
					}
				}
			}else{
				resultMap.put("code", 2);
				resultMap.put("msg", "权限编码已存在");
			}
			
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 根据权限，获取菜单（树形）
	 * @return
	 */
	private int menuLevel01 = 0;
	private int menuLevel02 = 0;
	private int menuLevel03 = 0;
	public Menu getMenuTree(Function fun) {
		Menu menu = managerDao.getParentMenu();
		menu.setIsFun(managerDao.checkFunLookAllMenu(fun.getFunctionId()));
		int functionId = fun.getFunctionId();
		Menu rsMenu = getChildMenu(menu, menu.getMenuId(),functionId);
		menuLevel01 = 0;
		menuLevel02 = 0;
		menuLevel03 = 0;
		return rsMenu;
	}
	private Menu getChildMenu(Menu menu, int menuId, int functionId){
		if(menu.getMenuLevel() == 1) menuLevel01 ++;
		if(menu.getMenuLevel() == 2) {
			menuLevel02 ++;
		};
		if(menu.getMenuLevel() == 3) menuLevel03 ++;
		String menuLevelStr = menuLevel01+"";
		if(menuLevel02 > 0) menuLevelStr += "-" + menuLevel02;
		if(menuLevel03 > 0) menuLevelStr += "-" + menuLevel03;
		menu.setMenuLevelFormat(menuLevelStr);
		if(menu.getChilds() > 0){
			List<Menu> childMenuList = managerDao.getMenusByParentId(menuId, functionId);
			if(childMenuList.size() > 0){
				List<Menu> tempList = new ArrayList<Menu>();
				for(Menu a : childMenuList){
					tempList.add(getChildMenu(a, a.getMenuId(), functionId));
					menu.setChildMenuList(tempList);
				}
			}
		}
		return menu;
	}
	/**
	 * 修改权限记录
	 * @param fun
	 * @return
	 */
	public Map<String, Object> updateFunction(HttpServletRequest request, Function fun) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String rsMsg = "";
		try {
			Function oldOrg = managerDao.getFunctionById(fun.getFunctionId());
			// 如果修改后的权限编码与原编码不一致，则检查是否与其他编码重复
			if(oldOrg != null && !fun.getFunctionCode().equals(oldOrg.getFunctionCode())){
				Function f = managerDao.getFunctionByCode(fun.getFunctionCode());
				if(f != null){
					rsMsg = "权限编码已存在";
					resultMap.put("code", 2);
					resultMap.put("msg", rsMsg);
					return resultMap;
				}
			}
			if(fun.getStateCode() == null){
				fun.setStateCode("0");
			}
			fun.setModifyDate(new Date());
			managerDao.updateFunction(fun);
			resultMap.put("code", 1);
			rsMsg = "权限修改成功";
			resultMap.put("msg", rsMsg);
			// 给权限分配菜单
			boolean isHaveMenu = managerDao.checkFunMenuById(fun.getFunctionId());
			String menuIds = request.getParameter("menuIds")==null?"":request.getParameter("menuIds");
			if(!menuIds.equals("")){
				try {
					if(isHaveMenu){
						managerDao.setFunctionMenus(fun.getFunctionId(), menuIds);
					}else{
						managerDao.addFunctionMenus(fun.getFunctionId(), menuIds);
					}
					rsMsg += "，保存权限菜单成功";
				} catch (Exception e) {
					resultMap.put("code", 3);
					rsMsg += "，但是给权限分配菜单时发生错误，错误信息："+e.getMessage();
					resultMap.put("msg", rsMsg);
				}
			}
		} catch (Exception e) {
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}
	/**
	 * 获取权限类型
	 * @return
	 */
	public List<Dictionaries> getDicList() {
		return managerDao.getDicList();
	}
	/**
	 * 根据权限类型ID，获取类型记录
	 * @param dicId
	 * @return
	 */
	public Dictionaries getDicById(int dicId) {
		return managerDao.getDicById(dicId);
	}
	/**
	 * 修改角色（修改角色中的权限）
	 * @param role
	 * @param funArray
	 * @return
	 */
	public Map<String, Object> updateRoleFun(Role role, String funArray) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			setRoleFunction(role, funArray);
			resultMap.put("code", 1);
			resultMap.put("msg", "角色权限修改成功");
		}catch(Exception e){
			resultMap.put("code", 0);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}

}